package masterjava.common.util;

import masterjava.common.logging.MasterLogger;

import java.io.*;
import java.net.URL;

/**
 * MasterJava.ru
 * <p/>
 * User: GKislin
 * Date: 02.04.11
 */
public class IOUtil {
    protected static final MasterLogger LOGGER = MasterLogger.get(IOUtil.class);

    public static URL getResourceSafely(String fileName) {
        return IOUtil.class.getClassLoader().getResource(fileName);
    }

    public static URL getResource(String fileName) {
        URL url = getResourceSafely(fileName);
        if (url == null) {
            throw LOGGER.getIllegalArgumentException(String.format("Resource file '%s' does not existed", fileName));
        }
        return url;
    }

    public static File getResourceAsFile(String fileName) {
        return urlToFile(getResource(fileName));
    }

    public static Reader getResourceAsReader(String fileName) {
        return streamToReader(getResourceAsStream(fileName));
    }

    private static InputStream getResourceAsStream(String fileName) {
        InputStream in = safeGetResourceAsStream(fileName);
        if (in == null) {
            throw LOGGER.getIllegalArgumentException(String.format("Resource file '%s' does not existed", fileName));
        }
        return in;
    }

    private static InputStream safeGetResourceAsStream(String fileName) {
        return IOUtil.class.getClassLoader().getResourceAsStream(fileName);
    }

    public static File urlToFile(URL url) {
        try {
            return new File(url.toURI());
        } catch (Exception e) {
            throw LOGGER.getIllegalArgumentException(String.format("Url '%s' is invalid", url), e);
        }
    }

    static Reader streamToReader(InputStream stream) {
        try {
            return new InputStreamReader(stream, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw LOGGER.getIllegalArgumentException("UTF-8 charsetName does not found", e);
        }
    }
}
